<template>
  <div class="html2canvas w-full h-full">
    <el-button type="primary" class="generate" @click="saveImg">生成</el-button>
    <el-button type="primary" class="preview" @click="preview">预览</el-button>
    <img ref="shareBox" class="w-full h-full" src="@/assets/img/htmlTocanvas/htmlbg.png" alt="HTML生成canvas图片并上传保存">
  </div>

  <!-- 预览 -->
  <el-dialog class='dailog' v-model="isPreview" title="HTML生成canvas图片并上传保存" width="90%" top="10vh">
    <iframe :src="zskUrl" frameborder="0" class="w-full h-full"></iframe>
  </el-dialog>
</template>


<script setup lang="ts">
import {
  ref,
} from 'vue'
import html2canvas from 'html2canvas'
import { ElMessage } from 'element-plus'

// 生成
let shareBox = ref()
const saveImg = () => {
  html2canvas(shareBox.value, {
    width: shareBox.value.offsetWidth,
    height: shareBox.value.offsetHeight,
    scale: 2
  }).then(function (canvas) {
    canvas.toBlob((blob) => {
      if (blob) {
        // 将html转成二进制流进行文件上传
        ElMessage({
          type: 'success',
          message: '生成canvas图片成功！'
        })
        console.log(blob, '图片blob资源');

        // 上传后返回预览地址，这里模拟一下
        zskUrl.value = URL.createObjectURL(blob);

      } else {
        ElMessage({
          type: 'error',
          message: '生成canvas图片失败，请稍后重试！'
        })
      }
    });
  })
}

// 预览
let isPreview = ref(false)
let zskUrl = ref()
const preview = () => {
  isPreview.value = true
}
</script>


<style lang="scss" scoped>
.html2canvas {
  position: relative;

  .generate {
    position: absolute;
    top: 100px;
    right: 50px;
  }

  .preview {
    position: absolute;
    top: 140px;
    right: 50px;
  }
}

</style>
<style lang="scss">
.dailog {
  height: 80vh;

  .el-dialog__body {
    height: 90%;
  }
}
</style>